package gl.java.mq;

import gl.java.umsp.UmspMessageDecoder;
import gl.java.umsp.UmspMessagePacker;
import gl.java.umsp.UmspMessageUnpacker;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClient {

    private static Logger log = LoggerFactory.getLogger(NettyClient.class);

    private volatile boolean isStop = false;
    private EventLoopGroup workerGroup;

    public static void stop(NettyClient nettyNetFrame) {
        nettyNetFrame.isStop = true;
        nettyNetFrame.workerGroup.shutdownGracefully();
    }

    public static NettyClient start(final String mHost, final int mPort, final SimpleChannelInboundHandler handler) {
        final NettyClient nettyNetFrame = new NettyClient();
        new Thread() {
            @Override
            public void run() {
                while (!nettyNetFrame.isStop) {
                    nettyNetFrame.listenForever(mHost, mPort, handler);
                    try {
                        log.warn("retry to connect after 3000ms");
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        return nettyNetFrame;
    }

    private void listenForever(final String mHost, final int mPort, final SimpleChannelInboundHandler handler) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        this.workerGroup = workerGroup;
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(
                            new UmspMessagePacker(),
                            new UmspMessageUnpacker(),
                            new UmspMessageDecoder(),
                            handler);
                }
            });

            ChannelFuture f = b.connect(mHost, mPort).sync(); // (5)
            f.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future)
                        throws Exception {
                    log.info("[success] Connect  MessageQueueService at " + mHost + ":" + mPort);

                }
            });
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            log.warn(e.toString());
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
